package com.wuwei.tms.workbench.controller;


import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wuwei.tms.listener.UploadDataListener;
import com.wuwei.tms.pojo.Borrow;
import com.wuwei.tms.pojo.Tool;
import com.wuwei.tms.setting.mapper.UserMapper;
import com.wuwei.tms.upload.DataDAO;
import com.wuwei.tms.utils.result.Result;
import com.wuwei.tms.utils.token.TokenUtil;
import com.wuwei.tms.workbench.mapper.BorrowMapper;
import com.wuwei.tms.workbench.mapper.ToolMapper;
import com.wuwei.tms.workbench.service.ToolService;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@RequestMapping("/T01/tool")
@RestController
//@CrossOrigin
public class ToolController {
    @Resource
    private ToolMapper toolMapper;

    @Resource
    private ToolService toolService;






    @PostMapping("/add")
    public Result<String> add (@RequestBody Tool tool) {
        //这里新增的工具的barcode不能重复
        LambdaQueryWrapper<Tool> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(tool.getBarcode()!=null,Tool::getBarcode,tool.getBarcode());
        if (toolMapper.selectCount(queryWrapper)!=0) {
            return Result.fail("工具编号重复！");
        }
        tool.setUserableNum(tool.getAllNumber());
        toolMapper.insert(tool);
        return Result.ok("添加成功");
    }

    @PostMapping("/update")
    public Result<String> update (@RequestBody Tool tool){

        return toolService.update(tool);


    }

    @PostMapping("/delete/{id}")
    public Result<String> delete (@PathVariable("id") Long id){
        toolMapper.deleteById(id);
        return Result.ok("删除成功");
    }


    /**
     * 按照工具名称，工具编号，件号进行分页查询
     * @param currentPage
     * @param pageSize
     * @param barcode
     * @param name
     * @param partNo
     * @return
     */
    @GetMapping("list/{currentPage}/{pageSize}/{barcode}/{name}/{partNo}/{consumeFlag}")
    public Result<List<Tool>> list (@PathVariable("currentPage") Integer currentPage , @PathVariable("pageSize") Integer pageSize,
                                    @PathVariable ("barcode") Long barcode,@PathVariable("name") String name
            ,@PathVariable("partNo") String partNo,@PathVariable("consumeFlag") Integer consumeFlag) {
        LambdaQueryWrapper<Tool> query = constructQuery(barcode, name, partNo, consumeFlag);
        IPage<Tool> page = new Page<>();
        page.setCurrent(currentPage);
        page.setSize(pageSize);
        IPage<Tool> selectPage = toolMapper.selectPage(page, query);
        List<Tool> records = selectPage.getRecords();
        return Result.ok(records);
    }


    /**
     * 按照工具名称，工具编号，件号进行分页查询
     * @param barcode
     * @param name
     * @param partNo
     * @return
     */
    @GetMapping("total/{barcode}/{name}/{partNo}/{consumeFlag}")
    public Result<Long> total (@PathVariable ("barcode") Long barcode,@PathVariable("name") String name
            ,@PathVariable("partNo") String partNo,@PathVariable("consumeFlag") Integer consumeFlag)  {
        LambdaQueryWrapper<Tool> queryWrapper = constructQuery(barcode, name, partNo, consumeFlag);
        Long count = toolMapper.selectCount(queryWrapper);
        return Result.ok(count);
    }

    /**
     * 构造查询条件，返回一个LambdaQueryWrapper
     * @param barcode
     * @param name
     * @param partNo
     * @param consumeFlag
     * @return
     */
    private LambdaQueryWrapper<Tool> constructQuery(Long barcode, String name,String partNo,Integer consumeFlag) {
        LambdaQueryWrapper<Tool> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(consumeFlag!=0,Tool::getConsumeFlag,consumeFlag)
                .like(barcode != -1,Tool::getBarcode,barcode)
                .like(!"_".equals(name),Tool::getName,name)
                .like(!"_".equals(partNo),Tool::getPartNo,partNo);
        return queryWrapper;
    }

    @Resource
    private DataDAO<Tool> toolDataDAO;

    /**
     * 上传工具清单，这个工具清单是一个excel格式，添加到数据库
     * @param file
     * @return
     */
    @PostMapping("upload")
    public Result<String> upload (@RequestParam("file") MultipartFile file)  {
        if (file.getSize() != 0) {
            try {
                EasyExcel.read(file.getInputStream(),Tool.class,new UploadDataListener<Tool>(toolDataDAO)).sheet().doRead();
                return Result.ok("上传成功");
            } catch (IOException e) {
                e.printStackTrace();
                return Result.fail(e.getMessage());
            }
        } else {
            return Result.fail("您没有上传任何文件");
        }
    }

    /**
     * 下载工具清单，这个工具清单是一个excel格式的文件
     * @param response
     */
    @SneakyThrows
    @GetMapping("download/all")
    public void download (HttpServletResponse response)  {
        LambdaQueryWrapper<Tool> wrapper = new LambdaQueryWrapper<>();
        List<Tool> records = toolMapper.selectList(wrapper);
        //把数据写成excel
        String filename = "tools.xlsx";
        EasyExcel.write(filename,Tool.class).sheet().doWrite(records);
        //将该文件返回给前端
        // 设置响应的内容类型为 Excel

        // 设置响应头，告诉浏览器该文件以附件形式下载
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=\"tools.xlsx\"");
        try(InputStream inputStream = new FileInputStream(filename);
            OutputStream outputStream = response.getOutputStream()){
            // 将文件的内容以流的形式写入响应对象
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @PutMapping("isolate/{id}/{status}")
    public Result<String> isolate (@PathVariable("id") Long id,@PathVariable("status") Integer status, HttpServletRequest request){
        LocalDateTime now = LocalDateTime.now();
        String token = request.getHeader("Authorization");
        Long empno = TokenUtil.getEmpnoFromToken(token);
        Integer integer = toolMapper.updateStatusById(id,status,now,empno);
        if (integer==1){
            return Result.ok("设置成功");
        }
        return Result.fail("设置失败！");
    }

    @Value("${prop.upload-folder}")
    private String UPLOAD_FOLDER;

    @Value("${prop.upload-url}")
    private String UPLOAD_URL;



    /**
     * 获取所有校验日期在一个月以内的计量工具
     * @return
     */
    @GetMapping("getUnUsedTool")
    public Result<List<Tool>> getUnUsedTool (){ List<Tool> list = toolService.getUnUsedTool();
        return Result.ok(list);
    }

    /**
     * 上传该工具有关的图片
     * @param file
     * @param id
     * @return
     */
    @SneakyThrows
    @PostMapping("image/{id}")
    public Result<String> image (@RequestParam("file") MultipartFile file, @PathVariable("id") Long id, HttpServletRequest request)  {
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        if (!"jpg,jpeg,gif,png".toUpperCase().contains(suffix.toUpperCase())) {
            return Result.fail("请选择jpg,jpeg,gif,png格式的图片");
        }

        if (file.getSize() != 0) {
            String uuid = UUID.randomUUID().toString();
            if (!new File(UPLOAD_FOLDER).exists()) {//如果文件夹不存在，则自动创建
                //检查文件夹是否创建成功
                boolean mkdirs = new File(UPLOAD_FOLDER).mkdirs();
                if (!mkdirs) {
                    return Result.fail("上传失败，图片所在的存储文件夹"+UPLOAD_FOLDER+"创建失败！");
                }
            }
            File file1 = new File(UPLOAD_FOLDER+ uuid +".jpg");
            file.transferTo(file1);
            //把file1更新到tool表中
            LocalDateTime now = LocalDateTime.now();
            String token = request.getHeader("Authorization");
            Long empno = TokenUtil.getEmpnoFromToken(token);
            Integer integer = toolMapper.updateImageSrcById(id, UPLOAD_URL + uuid + ".jpg",now,empno);
            if (integer==1){
                return Result.ok(UPLOAD_URL+uuid +".jpg");
            }
            return Result.fail("修改失败！");
        }
        return Result.fail("您没有上传任何文件");
    }

    /**
     * 把t_tool表的id对应的image_src设置为空
     * @param id
     * @return
     */
    @DeleteMapping("image/deleteImage/{id}")
    public Result<String> image (@PathVariable("id") Long id, HttpServletRequest request)  {
        LocalDateTime now = LocalDateTime.now();
        String token = request.getHeader("Authorization");
        Long empno = TokenUtil.getEmpnoFromToken(token);
        Integer integer = toolMapper.updateImageSrcToNull(id,now,empno);
        if (integer==1){
            return Result.ok("删除成功");
        }
        return Result.fail("删除失败！");
    }
    @GetMapping("getHangCaiList")
    public Result<List<Tool>> getHangCaiList(){
        LambdaQueryWrapper<Tool> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Tool::getConsumeFlag,4).le(Tool::getUserableNum,20);
        List<Tool> tools = toolMapper.selectList(queryWrapper);
        return Result.ok(tools);
    }
}
